// We're calculating the gradients on the fly, and then
// we're looking up normalized pre-calculated values.
// The precalculated values are stored in a 2D array,
// though only one dimension is actually used. 
// Basically, all the values in y direction are the
// same, (x, 0.3) and (x, 0.8) should give the same
// result. This is done mainly for debug purposes -
// 2D texture can be displayed as a layer and we
// can visually check what are the values there.

uniform sampler2D cdf;

vec4 dataInterpolation(sampler3D data, const vec3 texCoordinates);

vec3 gradient( sampler3D data, const float scaleValue, const vec3 texCoord, const float voxelSpacing )
{
      vec3 delX = vec3(voxelSpacing, 0.0, 0.0);
      vec3 delY = vec3(0.0, voxelSpacing, 0.0);
      vec3 delZ = vec3(0.0, 0.0, voxelSpacing);
      //
      // Sample the texture
      //
      vec3 newVector = vec3(gl_TexCoord[0].xyz);
      vec3 newVectorX = newVector + delX;
      vec3 newVectorY = newVector + delY;
      vec3 newVectorZ = newVector + delZ;
      vec4 cx = dataInterpolation(data, newVectorX);
      vec4 cy = dataInterpolation(data, newVectorY);
      vec4 cz = dataInterpolation(data, newVectorZ);
      //
      // Calculate the gradient vector at the sample position.
      // 	
      vec3 grad;
      grad.x = (cx.a-scaleValue);
      grad.y = (cy.a-scaleValue);
      grad.z = (cz.a-scaleValue);
	  
	  float gradLength = length(grad);
	  if(gradLength < 0.05)
		return grad;

	vec2 lookupCoord = vec2(gradLength, 0.2);//y coord can be anything
	vec4 lookupValue = texture2D(cdf, lookupCoord);
	float newGradientLength = lookupValue.x;
	  
	vec3 newGradient;
	
	newGradient.x = grad.x * newGradientLength / gradLength;
	newGradient.y = grad.y * newGradientLength / gradLength;
	newGradient.z = grad.z * newGradientLength / gradLength;
	  
	return newGradient;
}

//check what is stored in the cdf texture! It seems right now I'm not storing the right values in rgb components!